<?php

namespace co2\dev\v0_0_0;

if(!function_exists('curl_init'))
throw new Exception('curl not installed');

class curl

{
	protected
		$response,
		$info,
		$headers,
		$body,
		$method='GET',
		$request=array
		(
			'body'	=> null
		)
		;

	public function
	__construct
	(
							$url,
		\stdClass	$headers=null,
		\stdClass	$options=null
	)
	{
		$this->request=(object)$this->request;
	
		$curl=curl_init($url);
		
		curl_setopt_array($curl,array
		(
			CURLOPT_RETURNTRANSFER	=> 	1,
			CURLOPT_HEADER					=>	1
		));
		
		if(is_object($options))
		
		{
			if(isset($options->method))
			$this->method=$options->method;
			
			if(isset($options->body))
			$this->request->body=$options->body;
		}
		
		switch($this->method)
		
		{
			case'POST':
			
				curl_setopt($curl,CURLOPT_POST,1);
				curl_setopt($curl,CURLOPT_POSTFIELDS,$this->request->body);
			
			break;
		}
		
		$this->response=curl_exec($curl);
		
		if(!$this->response)
		throw new Exception('curl transfer failed');
		
		$this->info=curl_getinfo($curl);
		
		$e=preg_split('/\r\n\r\n/',$this->response,2);
		
		$this->headers=$e[0];
		
		$this->body=isset($e[1])?$e[1]:null;
		
		curl_close($curl);
	}
	
	public function
	getResponse
	(
	
	)
	{
		return $this->response;
	}
	
	public function
	getInfo
	(
		$index=null
	)
	{
		$info=(object) $this->info;
		
		return
			!is_null($index) && isset($info->$index)
			?$info->$index
			:$info;
	}
	
	public function
	getBody
	(
	
	)
	{
		return $this->body;
	}
	
	public function
	getHeaders
	(
		$index=null
	)
	
	{
		if(is_bool($index) && !$index)
		return $this->headers;
		
		$headers=String::gi($this->headers)->toLines();
		
		if(is_int($index))
		return $headers[0];
		
		return $headers;
	}
	
	public function
	__toString()
	
	{
		return $this->body;
	}
}
